﻿namespace MSRI.SmsService
{
    using Microsoft.Win32;
    using MSRI.HelperClasses;
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.Runtime.CompilerServices;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Ipc;
    using System.Runtime.Serialization.Formatters;
    using System.Threading;
    using System.Windows.Forms;

    public class SmsServiceClass
    {
        private string _SubscriberName = "";
        private CallbackSinkClass CallBackSink;
        private IpcChannel ipcChannel;
        private SmsPublishClass Publisher;

        public event OnDeliveryReportDelegate OnDeliveryReportReceived;

        internal event OnMessageReceivedDelegate OnMessageReceived;

        public event OnSmsReceivedDelegate OnSmsReceived;

        public SmsServiceClass(string SubscriberName)
        {
            if ((SubscriberName != null) && (SubscriberName.Trim().Length != 0))
            {
                Process process = null;
                string str = null;
                string str2 = null;
                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\MSR India\SmsDesktopAgent");
                if (key != null)
                {
                    str = (string) key.GetValue("applicationpath", string.Empty);
                    str2 = (string) key.GetValue("workingdirectory", string.Empty);
                }
                if (str != null)
                {
                    Process[] processes = Process.GetProcesses();
                    bool flag = false;
                    foreach (Process process2 in processes)
                    {
                        if (process2.ProcessName == "SmsDesktopAgent")
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        process = new Process();
                        process.StartInfo.FileName = str;
                        process.StartInfo.WorkingDirectory = str2;
                        process.Start();
                        process.WaitForInputIdle();
                        process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
                        Application.DoEvents();
                        Thread.Sleep(0x1388);
                    }
                }
                this._SubscriberName = SubscriberName;
                BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider();
                serverSinkProvider.TypeFilterLevel = TypeFilterLevel.Full;
                BinaryClientFormatterSinkProvider clientSinkProvider = new BinaryClientFormatterSinkProvider();
                Hashtable properties = new Hashtable();
                properties["name"] = "MSRI_Sms_Server";
                properties["portName"] = SubscriberName;
                properties["timeout"] = "-1";
                properties["socketCacheTimeout"] = "-1";
                properties["connectionTimeout"] = "-1";
                properties["exclusiveAddressUse"] = false;
                properties["typeFilterLevel"] = "Full";
                this.ipcChannel = new IpcChannel(properties, clientSinkProvider, serverSinkProvider);
                ChannelServices.RegisterChannel(this.ipcChannel, false);
                this.Publisher = (SmsPublishClass) Activator.GetObject(typeof(SmsPublishClass), "ipc://MSRI_Sms_Server/MSRI_Sms_Server.rem");
                if (this.Publisher == null)
                {
                    if (this.ipcChannel != null)
                    {
                        ChannelServices.UnregisterChannel(this.ipcChannel);
                    }
                    throw new Exception("Error:Failed to communicate with Sms Server Desktop Agent");
                }
                this.CallBackSink = new CallbackSinkClass();
                this.CallBackSink.OnDeliveryReportReceived += new OnDeliveryReportDelegate(this.CallBackSink_OnDeliveryReportReceived);
                this.CallBackSink.OnMessageReceived += new OnMessageReceivedDelegate(this.CallBackSink_OnMessageReceived);
                this.CallBackSink.OnSmsReceived += new OnSmsReceivedDelegate(this.CallBackSink_OnSmsReceived);
                this.CallBackSink.IsClientConnected += new IsClientConnectedDelegate(this.CallBackSink_IsClientConnected);
                try
                {
                    if (!this.Publisher.RegisterClient(this._SubscriberName, new OnMessageReceivedDelegate(this.CallBackSink.HandleMessageReceived), new OnSmsReceivedDelegate(this.CallBackSink.HandleSmsReceived), new OnDeliveryReportDelegate(this.CallBackSink.HandleDeliveryReportReceived), new IsClientConnectedDelegate(this.CallBackSink.HandleIsClientConnected)))
                    {
                        throw new Exception("Error:Unable to register service name");
                    }
                    this.Publisher.Client2Server_Connected(SubscriberName);
                    return;
                }
                catch
                {
                    this.CallBackSink = null;
                    if (this.ipcChannel != null)
                    {
                        ChannelServices.UnregisterChannel(this.ipcChannel);
                    }
                    this.Publisher = null;
                    throw new Exception("Error:Please restart the Sms Desktop Agent or refresh the Client List");
                }
            }
            if (this.ipcChannel != null)
            {
                ChannelServices.UnregisterChannel(this.ipcChannel);
            }
            throw new Exception("Error:Invalid SubscriberName");
        }

        private bool CallBackSink_IsClientConnected()
        {
            return true;
        }

        private void CallBackSink_OnDeliveryReportReceived(DeliveryReportClass DeliveryReport)
        {
            if (this.OnDeliveryReportReceived != null)
            {
                this.OnDeliveryReportReceived(DeliveryReport);
            }
        }

        private void CallBackSink_OnMessageReceived(string Message)
        {
            if (this.OnMessageReceived != null)
            {
                this.OnMessageReceived(Message);
            }
        }

        private SmsResponseClass CallBackSink_OnSmsReceived(SmsClass SmsMessage)
        {
            if (this.OnSmsReceived != null)
            {
                return this.OnSmsReceived(SmsMessage);
            }
            return null;
        }

        ~SmsServiceClass()
        {
            try
            {
                if (this.Publisher != null)
                {
                    this.Publisher.DisposeClient(this._SubscriberName);
                    this.Publisher.Client2Server_Disconnected(this._SubscriberName);
                }
                if (this.ipcChannel != null)
                {
                    ChannelServices.UnregisterChannel(this.ipcChannel);
                }
            }
            catch
            {
            }
        }

        internal void SendMessage(string Message)
        {
            if (this.Publisher != null)
            {
                this.Publisher.Client2Server_SendMessage(this._SubscriberName, Message);
            }
        }

        public void SendSms(SmsClass Message)
        {
            if (this.Publisher != null)
            {
                this.Publisher.Client2Server_SendSms(this._SubscriberName, new SmsClass(Message));
            }
        }

        public bool IsConnected
        {
            get
            {
                return ((this.Publisher != null) && this.Publisher.IsConnected);
            }
        }

        public string SubscriberName
        {
            get
            {
                return this._SubscriberName;
            }
        }
    }
}

